package edu.pku.sei.sct.primitives;

import java.util.List;

import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EObject;

import edu.pku.sei.AMT.ObjectVariable;
import edu.pku.sei.AMT.Section;
import edu.pku.sei.ocl.evaluation.Context;
import edu.pku.sei.ocl.utilities.OCLConstant;
import edu.pku.sei.sct.evaluation.SCTEnvironment;

public class MatchVariable extends AbstractPrimitive {
	
	private static final String ID = "MatchVariable";
	

	public MatchVariable(SCTEnvironment e) {
		super(e);
		// TODO Auto-generated constructor stub
	}

	/**
	 * argv[0] = variable
	 * argv[1] = List\<String\>
	 * argv[2] = context
	 */
	@SuppressWarnings("unchecked")
	@Override
	public Object execute(Object... argv) {
		ObjectVariable v = (ObjectVariable) argv[0];
		List<String> expr = (List<String>)argv[1];
		Context context = (Context)argv[2];
		
		EvaluateExpression ee = (EvaluateExpression) this.getSctEnvironment().getPrimitive(EvaluateExpression.ID);
		EClass type = getSctEnvironment().getType(v.getScope(), v.getType());
		List<Integer> oids = this.getSctEnvironment().manager.getObjectIDs(v.getScope(), type);
		
		for(Integer i : oids) {
			EObject o = this.getSctEnvironment().manager.getObject(v.getScope(), i);
			Context c = context.getCopy();
			c.putValue(v.getName(), o);
			Boolean returnvalue = (Boolean) ee.execute("check",expr,c);
			if(returnvalue)
				return c;
		}
		
		return OCLConstant.OCLInvalid;
	}

	@Override
	public String getID() {
		return ID;
	}

}
